<template>
	<div class="chat_wrapper">
		<chatheader></chatheader>
		<div class="chat_container">
			<div class="chat_content" ref="chatList">
				<div class="no_chat" v-if="list.length == 0">
					<div class="chat_t">
						<!-- <img :src="icon_t" width="24" /> -->
						<GuZhang width="1.5rem" height="1.73rem"></GuZhang>
						<span>你好，我是鸡小蟹同学！</span>
					</div>
					<div class="chat_desc">
						你的个人专属AI智能体，初次见面很开心呢！我可以回答你的各种问题，给你娱乐、工作和学习提供帮助，还能随时陪你聊天。嗯，你想问点什么呢？
						<!-- <img :src="shouzhiIcon" width="16" /> -->
						<shouzhi width="1rem" height="1.31rem"></shouzhi>
					</div>
					<ul class="default-list">
						<li v-for="(item, index) in defaultList" :key="index" @click="handelSug(item)">
							<i :class="['img_'] + index"></i>
							{{ item }}
						</li>
					</ul>
				</div>
				<div class="chat_List" v-else>
					<div v-for="(item, index) in list" :key="index">
						<div v-if="item.chatType == ChatType.user">
							<user :message="item" :index="index"></user>
						</div>
						<div v-else-if="item.chatType == ChatType.robot">
							<robot :message="item" :index="index" :currentIndex="currentIndex" @on-resend="resendMsg" @on-clear-context="clearContext(index)" @on-like="dolike(index)" @on-unlike="dounlike(index)" @on-suggestion="handelSug"></robot>
						</div>
						<div class="clearContext" v-else-if="item.chatType == ChatType.clear">
							<Divider>已清除上下文</Divider>
						</div>
					</div>
				</div>
			</div>
			<div class="chat_bottom">
				<div class="tool">
					<div class="tool_btn" @click="getInspiration">
						<!-- <img :src="lgIcon" width="24" /> -->
						<LingGan width="1.5rem" height="1.5rem"></LingGan>
						<span>聊天灵感</span>
					</div>
					<!-- <div class="tool_btn tool_right" @click="clearChat">
						<DuiHua width="1.5rem" height="1.5rem"></DuiHua>
						<span>创建新对话</span>
					</div> -->
				</div>
				<div class="input_container" v-show="!isVoice">
					<Input v-model="inputStr" type="textarea" placeholder="您可以在此输入问题或点击麦克风图标进行语音输入" maxlength="2000" @keydown.native="KeyDownFn" />
					<!-- <img :src="videoIcon"  width="24" /> -->
					<div class="yuyin" @click="startVoice">
						<YuYin width="1.5rem" height="1.5rem"></YuYin>
					</div>
				</div>
				<div class="voice_bg" v-show="isVoice">
					<!-- <img class="pausebtn" :src="pausedIcon" width="24" @click="pauseVoice" /> -->
					<div class="pausebtn" @click="pauseVoice">
						<YuYin2 width="1.5rem" height="1.5rem"></YuYin2>
					</div>
					<div class="voice_content">{{ inputStr }}</div>
					<div class="voice_loading">
						<!-- <img :src="voiceLoadingIcon" height="18" /> -->
						<YuYin3 width="4.5rem" height="1.13rem"></YuYin3>
						<span>正在倾听中.......</span>
					</div>
				</div>
				<div class="bottom_btn">
					<!-- <img :src="tansuoIcon" style="cursor: pointer"  /> -->
					<div class="tansuo" @click="gotoExplore">
						<TanSuo width="1.5rem" height="1.5rem"></TanSuo>
						<span class="tansuo-title">探索</span>
					</div>
					<!-- <TanSuo width="6.75rem" height="3rem"></TanSuo> -->
					<Button @click="send">发送</Button>
				</div>
				<div class="footer">
					<span>对话内容由AI生成，仅供参考</span>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import Robot from './components/robot.vue'
import User from './components/user.vue'
// import Suggestion from './components/suggestion.vue'
import chatheader from './header.vue'
import GuZhang from '@/components/svg/guzhang.vue'
import shouzhi from '@/components/svg/shouzhi.vue'
import LingGan from '@/components/svg/linggan.vue'
import YuYin from '@/components/svg/yuyin.vue'
import YuYin3 from '@/components/svg/yuyin3.vue'
import YuYin2 from '@/components/svg/yuyin2.vue'
import TanSuo from '@/components/svg/tansuo.vue'
import { ChatType } from './components/util'
// import icon_t from '@/assets/images/chat/guzhang.svg'
// import lgIcon from '@/assets/images/chat/linggan.svg'
// import newChatIcon from '@/assets/images/chat/duihua.svg'
// import videoIcon from '@/assets/images/chat/yuyin.svg'
// import voiceLoadingIcon from '@/assets/images/chat/yuyin3.svg'
// import pausedIcon from '@/assets/images/chat/yuyin2.svg'
// import shouzhiIcon from '@/assets/images/chat/shouzhi-2.svg'
// import TanSuo from '@/components/svg/tansuo.vue'
import tansuoIcon from '@/assets/images/chat/tansuo.png'
import Clipboard from 'clipboard'
export default {
	components: {
		Robot,
		User,
		// Suggestion,
		chatheader,
		TanSuo,
		GuZhang,
		shouzhi,
		LingGan,
		YuYin,
		YuYin3,
		YuYin2
	},
	data() {
		return {
			message: {
				// 生成一段带有代码的markdown格式数据
				content: ''
			},
			tansuoIcon,
			inputStr: '',
			defaultList: ['打开机械革命电竞控制台', '把电脑的音量设置为20', '我需要写一封商务合作邮件，你能帮我构思一下内容吗？', '游戏中作为英勇战士，你通常如何与队友沟通并制定战术？'],
			list: [],
			isloading: false,
			ChatType: ChatType,
			currentIndex: 0,
			currentMsg: '',
			isVoice: false,
			timer: null,
			count: 60,
			hisList: [],
			clipboardCode: null
		}
	},
	watch: {
		list: {
			handler(newVal, oldVal) {
				this.scrollToBottom()
			},
			deep: true
		}
	},
	// 在数据更新时，重新创建 Clipboard 实例
	updated() {
		if (this.clipboardCode) {
			this.clipboardCode.destroy()
		}
		this.createClipboardInstance()
	},
	methods: {
		createClipboardInstance() {
			this.clipboardCode = new Clipboard('.copy-btn')
			this.clipboardCode.on('success', (e) => {
				e.clearSelection()
				this.$Message.success({
					content: '复制成功'
				})
			})
			this.clipboardCode.on('error', () => {
				this.$Message.error({
					content: '复制失败'
				})
			})
		},
		send() {
			if (!this.inputStr || !this.inputStr.trim()) {
				return false
			} else {
				this.sendMessage(this.inputStr.trim())
				this.inputStr = ''
			}
		},
		sendMessage(msg) {
			if (!this.isloading) {
				this.list.push({
					chatType: ChatType.user,
					content: msg
				})
				this.currentMsg = msg
				this.getAnswer(msg)
			} else {
				this.$Message.error('请等机器人回复后再发送哦~')
			}
		},
		async getAnswer(msg) {
			this.isloading = true
			this.list.push({
				chatType: ChatType.robot,
				content: '',
				suglist: [],
				islike: false,
				isunlike: false,
				isLoading: true
			})
			this.currentIndex = this.list.length - 1
			let hisList = this.getHisList()
			hisList.push({
				role: 'user',
				content: msg
			})
			let res = await chrome.webview.hostObjects.chatHelper.SendChatAsync(JSON.stringify(hisList))
			res = JSON.parse(res)
			if (res.code !== '0') {
				this.list[this.currentIndex].isLoading = false
				this.isloading = false
				this.list[this.currentIndex].content = res.data
			}
		},
		clearChat() {
			this.list = []
			this.isloading = false
			this.currentIndex = 0
			this.currentMsg = ''
			this.inputStr = ''
			// localSave('chatlist', JSON.stringify(this.list))
		},
		scrollToBottom() {
			this.$nextTick(() => {
				let scrollElem = this.$refs.chatList
				scrollElem.scrollTo({ top: scrollElem.scrollHeight, behavior: 'smooth' })
			})
		},
		async getSuggestionList() {
			let hisList = this.getHisList()
			try {
				let result = await chrome.webview.hostObjects.chatHelper.RecommendAsync(JSON.stringify(hisList))
				result = JSON.parse(result)
				if (result instanceof Object) {
					let recommends = Object.values(result)
					console.log(this.list)
					console.log(this.currentIndex)
					this.list[this.currentIndex].suglist = recommends
					// localSave('chatlist', JSON.stringify(this.list))
				}
			} catch (e) {}
		},
		handelSug(obj) {
			this.inputStr = obj
		},
		receiveMessage(content) {
			if (content === 'data: [DONE]') {
				this.list[this.currentIndex].isLoading = false
				this.isloading = false
				// localSave('chatlist', JSON.stringify(this.list))
				this.hisList = [...this.list]
				this.getSuggestionList()
			} else {
				this.list[this.currentIndex].content += content
			}
		},
		resendMsg() {
			this.getAnswer(this.currentMsg)
		},
		getHisList() {
			// let localList = localRead('chatlist')
			let hisList = []
			// if (localList) {
			let local = [...this.hisList]
			let index = local.findLastIndex((x) => x.chatType === ChatType.clear)
			let list = index === -1 ? [...local] : local.slice(index + 1)
			list.forEach((item) => {
				if (item.chatType === ChatType.user) {
					hisList.push({
						role: 'user',
						content: item.content
					})
				} else if (item.chatType === ChatType.functionCall) {
					hisList.push(item.tollcall)
				} else if (item.chatType === ChatType.robot) {
					hisList.push({
						role: 'assistant',
						content: item.content
					})
				}
			})
			// }
			return hisList
		},
		async clearContext(index) {
			this.list.push({
				chatType: ChatType.clear
			})
			this.hisList = [...this.list]
			await chrome.webview.hostObjects.chatHelper.ClearContextAsync(this.list[index].chatId)
			// this.getChatList()
			// localSave('chatlist', JSON.stringify(this.list))
		},
		async getInspiration() {
			let res = await chrome.webview.hostObjects.chatHelper.ChatInspirationAsync()
			this.inputStr = res
		},
		async startVoice() {
			this.inputStr = ''
			this.dotimer()
			await chrome.webview.hostObjects.form.OnPageEvent('startRecord')
		},
		async stopVoice() {
			await chrome.webview.hostObjects.form.OnPageEvent('stopRecord')
		},
		pauseVoice() {
			this.isVoice = false
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
			this.stopVoice()
		},
		dotimer() {
			let TIME_COUNT = 60
			if (!this.timer) {
				this.count = TIME_COUNT
				this.isVoice = true
				this.timer = setInterval(() => {
					if (this.count > 0 && this.count <= TIME_COUNT) {
						this.count -= 1
					} else {
						this.isVoice = false
						clearInterval(this.timer)
						this.timer = null
						this.stopVoice()
					}
				}, 1000)
			}
		},
		setVoiceText(content) {
			this.inputStr = content
		},
		async dolike(index) {
			await chrome.webview.hostObjects.chatHelper.AddLikeAsync(this.list[index].id)
			this.list[index].islike = !this.list[index].islike
		},
		async dounlike(index) {
			await chrome.webview.hostObjects.chatHelper.AddDislikeAsync(this.list[index].id)
			this.list[index].isunlike = !this.list[index].isunlike
		},
		async gotoExplore() {
			await chrome.webview.hostObjects.chatHelper.StopTTSAsync()
			chrome.webview.hostObjects.sync.form.OnPageEvent('openAgentPage')
		},
		async getChatList() {
			let res = await chrome.webview.hostObjects.chatHelper.QueryXiaoXieChatMsgsAsync()
			let result = JSON.parse(res)
			console.log(result)
			let list = []
			if (result.length === 0) {
				this.list = []
				this.hisList = []
			} else {
				result.forEach((item) => {
					list.push({
						chatType: ChatType.user,
						content: item.prompt,
						in_context: item.in_context
					})
					list.push({
						chatType: ChatType.robot,
						content: item.completion,
						suglist: [],
						islike: item.zan,
						isunlike: item.cai,
						isLoading: false,
						id: item.id,
						chatId: item.chat_id,
						in_context: item.in_context
					})
				})
				this.list = [...list]
				// 处理上下文
				let idx = this.list.findLastIndex((x) => !x.in_context)
				if (idx !== -1) {
					this.list.splice(idx + 1, 0, {
						chatType: ChatType.clear
					})
				}
				this.currentIndex = this.list.findLastIndex((x) => x.chatType === ChatType.robot)
				let lastidx = this.list.findLastIndex((x) => x.chatType === ChatType.user)
				this.currentMsg = this.list[lastidx].content
				this.hisList = [...this.list]
				this.getSuggestionList()
			}
		},
		KeyDownFn(e) {
			if (e.keyCode === 13) {
				e.cancelBubblue = true
				e.stopPropagation()
				e.preventDefault()
				if (e.shiftKey) {
					// shift + 回车
					let sInd = e.srcElement.selectionStart
					let eInd = e.srcElement.selectionEnd
					let val = this.inputStr
					this.inputStr = val.substring(0, sInd) + '\n' + val.substring(eInd)
				} else {
					// 回车
					this.send()
				}
			}
		},
		setFunctionCall(json) {
			json = JSON.parse(json)
			this.hisList.push({
				chatType: ChatType.functionCall,
				tollcall: json
			})
		}
	},

	mounted() {
		this.getChatList()
		console.log(window.screen.width)
		window.receiveMessage = (param) => {
			this.receiveMessage(param)
		}
		window.setVoiceText = (param) => {
			this.setVoiceText(param)
		}
		window.startVoice = () => {
			this.startVoice()
		}
		window.getChatList = () => {
			this.getChatList()
		}
		window.stopRecord = () => {
			this.pauseVoice()
		}
		window.setFunctionCall = (param) => {
			this.setFunctionCall(param)
		}
		this.createClipboardInstance()
		// let localList = localRead('chatlist')
		// if (localList) {
		// 	this.list = [...JSON.parse(localList)]
		// }
	},
	beforeDestroy() {
		if (this.clipboardCode) {
			this.clipboardCode.destroy()
		}
	}
}
</script>
<style lang="less" scoped>
.chat_wrapper {
	background: var(--bg-color);
	// border: 0.13rem solid var(--bg-color);
	box-shadow: inset 0rem 0.06rem 0.19rem 0rem rgba(255, 255, 255, 0.5);
	box-shadow: 0rem 0.06rem 0.31rem 0rem rgba(255, 255, 255, 0.5);
	// border-radius: 2rem;
	.chat_container {
		position: absolute;
		top: 5.25rem;
		width: 100%;
		.chat_content {
			height: calc(100vh - 290px);
			overflow: auto;
			padding: 0 1.5rem;
			.no_chat {
				background: var(--chat-noChat-bg);
				box-shadow: 0rem 0rem 0.5rem 0rem rgba(219, 218, 218, 0.3);
				border-radius: 0.5rem;
				padding: 1.5rem;
				.chat_t {
					display: flex;
					align-items: center;
					span:first-child {
						margin-right: 0.8rem;
					}
					span {
						font-family: PingFangSC-Semibold;
						font-size: 1.17rem;
						color: var(--chat-pure-title);
						letter-spacing: 0;
						font-weight: 600;
					}
				}
				.chat_desc {
					font-family: PingFangSC-Regular;
					font-size: 1.17rem;
					color: var(--chat-pure-desc);
					letter-spacing: 0;
					line-height: 2rem;
					font-weight: 400;
					margin-top: 1.13rem;
					img {
						vertical-align: middle;
					}
				}
				.default-list {
					list-style: none;
					margin-top: 0.5rem;
					li {
						cursor: pointer;
						background-image: var(--chat-defaultList-bg);
						border-radius: 0.5rem;
						height: 4.2rem;
						margin-top: 1.5rem;
						font-family: PingFangSC-Regular;
						font-size: 1.13rem;
						color: var(--chat-defaultList-color);
						letter-spacing: 0;
						// line-height: 2rem;
						font-weight: 400;
						display: flex;
						align-items: center;
						padding: 0 1.2rem;
						i {
							width: 1.5rem;
							height: 1.5rem;
							display: inline-block;
							vertical-align: middle;
							margin-right: 1rem;
						}
						.img_0 {
							height: 1.5rem;
							height: 1.5rem;
							background-size: contain;
							background-repeat: no-repeat;
							background-image: url('../../assets/images/chat/pure/1.svg');
						}
						.img_1 {
							height: 1.5rem;
							height: 1.5rem;
							background-size: contain;
							background-repeat: no-repeat;
							background-image: url('../../assets/images/chat/pure/2.svg');
						}
						.img_2 {
							height: 1.5rem;
							height: 1.5rem;
							background-size: contain;
							background-repeat: no-repeat;
							background-image: url('../../assets/images/chat/pure/3.svg');
						}
						.img_3 {
							height: 1.5rem;
							height: 1.5rem;
							background-size: contain;
							background-repeat: no-repeat;
							background-image: url('../../assets/images/chat/pure/4.svg');
						}
					}
				}
			}
			.chat_List {
				// margin-top: 1.5rem;
				.clearContext {
					/deep/.ivu-divider-inner-text {
						color: #aaaaaa;
						font-size: 14px;
					}
				}
			}
		}
		.chat_bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100vw;
			padding: 1.5rem;
			.tool {
				font-size: 13px;
				color: #aaaaaa;
				display: flex;
				align-items: center;
				.tool_des {
					margin-left: 10px;
				}
				.tool_btn {
					display: flex;
					align-items: center;
					cursor: pointer;
					font-family: PingFangSC-Semibold;
					font-size: 1.13rem;
					color: #f38800;
					letter-spacing: 0;
					font-weight: 600;
					span:first-child {
						margin-right: 0.5rem;
					}
				}
				.tool_right {
					margin-left: auto;
				}
			}
			.input_container {
				margin-top: 1rem;
				position: relative;
				.yuyin {
					position: absolute;
					right: 1.5rem;
					bottom: 1rem;
					cursor: pointer;
				}
				/deep/.ivu-input {
					padding: 1.13rem 1.5rem;
					padding-bottom: 2.5rem;
					padding-right: 2rem;
					height: 6.63rem;
					opacity: 1;
					background: var(--chat-input-bg);
					border: 0.13rem solid var(--chat-input-border);
					box-shadow: inset 0rem 0.06rem 0.44rem 0rem rgba(229, 229, 229, 0.5);
					border-radius: 0.5rem;
					resize: none;
					color: var(--chat-input-color);
				}
			}
			.voice_bg {
				margin-top: 1rem;
				position: relative;
				opacity: 0.9;
				background: var(--chat-input-bg);
				border: 0.13rem solid var(--chat-input-border);
				box-shadow: inset 0rem 0.06rem 0.44rem 0rem rgba(229, 229, 229, 0.5);
				border-radius: 0.5rem;
				min-height: 6.63rem;
				.voice_content {
					padding: 1.13rem 1.5rem 2rem 1.5rem;
					word-wrap: break-word;
					word-break: normal;
				}
				.voice_loading {
					position: absolute;
					bottom: 1rem;
					left: calc(50% - 73px);
					span:first-child {
						margin-right: 1rem;
					}
					span {
						font-family: PingFangSC-Regular;
						font-size: 1.13rem;
						color: var(--chat-voice-color);
						letter-spacing: 0;
						font-weight: 400;
					}
				}
				.pausebtn {
					position: absolute;
					right: 1.5rem;
					bottom: 1rem;
					cursor: pointer;
				}
			}
			.bottom_btn {
				margin-top: 24px;
				display: flex;
				justify-content: space-between;
				.tansuo {
					background-image: url('../../assets/images/tansuo.svg');
					width: 6.75rem;
					height: 3rem;
					padding: 0.81rem 1.25rem;
					background-size: contain;
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					align-items: center;
					cursor: pointer;
					.tansuo-title {
						font-family: PingFangSC-Semibold;
						font-size: 1.13rem;
						color: #ffffff;
						letter-spacing: 0;
						line-height: 2rem;
						font-weight: 600;
					}
				}
				// img {
				// 	width: 6.75rem;
				// 	height: 3rem;
				// }
				/deep/.ivu-btn {
					background-image: linear-gradient(136deg, #ffb346 0%, #fe8e00 100%);
					border-radius: 1.75rem;
					padding: 0.53rem 1.35rem;
					height: 3rem;
					font-size: 1.13rem;
					color: #ffffff;
					font-weight: 600;
					border-color: var(--ivu-btn-border-color);
					line-height: 2rem;
					border: none;
					box-shadow: none;
				}
			}
		}
	}
	.footer {
		text-align: center;
		span {
			font-family: PingFangSC-Regular;
			font-size: 0.88rem;
			color: var(--chat-footer-tips, #c6c6c6);
			letter-spacing: 0;

			font-weight: 400;
		}
	}
}
</style>
